package api

import (
	"buding-ai/internal/service"
	"buding-ai/internal/web/dto"
	"buding-ai/internal/web/middleware"
	"buding-ai/internal/web/response"
	"buding-ai/pkg/utils/jwt"
	"github.com/gin-gonic/gin"
)

// AuthApi 授权API结构体
type AuthApi struct {
	router  *gin.RouterGroup
	authSrv *service.AuthService
	BaseApi
}

// NewAuthApi 创建授权API实例
func NewAuthApi(router *gin.RouterGroup) *AuthApi {
	api := &AuthApi{
		router:  router,
		authSrv: service.NewAuthService(),
	}
	api.router.POST("/login", api.login)
	api.router.GET("/current", middleware.JWTAuth(), api.current)
	api.router.POST("/restPassword", middleware.JWTAuth(), api.restPassword)
	return api
}

// login 用户登录
func (api *AuthApi) login(ctx *gin.Context) {
	var loginDTO dto.LoginDTO
	if err := ctx.ShouldBindJSON(&loginDTO); err != nil {
		response.ParamBindError(ctx, err)
		return
	}
	//登录
	login, err := api.authSrv.Login(loginDTO)
	if err != nil {
		response.InternalError(ctx, "登陆失败,", err)
		return
	}
	response.SuccessWithData(ctx, login)
}

// current 获取当前登录用户信息
func (api *AuthApi) current(ctx *gin.Context) {
	// 从上下文中获取JWT声明
	claims, exists := ctx.Get("claims")
	if !exists {
		response.Unauthorized(ctx, "未认证")
		return
	}
	// 将声明转换为JWT声明对象
	jwtClaims, ok := claims.(*jwt.Claims)
	if !ok {
		response.InternalError(ctx, "无效的JWT声明", nil)
		return
	}

	one, err := api.authSrv.GetOne(jwtClaims.UserID)
	if err != nil {
		response.InternalError(ctx, "获取用户失败,", err)
		return
	}
	response.Success(ctx, "获取当前用户信息成功", one)
}

// restPassword 重置密码
func (api *AuthApi) restPassword(ctx *gin.Context) {
	var resetDTO dto.PasswordResetDTO
	if err := ctx.ShouldBindJSON(&resetDTO); err != nil {
		response.ParamBindError(ctx, err)
		return
	}
	if err := api.authSrv.RestPassword(resetDTO); err != nil {
		response.InternalError(ctx, "密码重置成功失败,", err)
	}
	response.Success(ctx, "密码重置成功", nil)
}
